<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-button type="primary" @click="addKLineDataVisible = true">{{$t('message.add-template')}}</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table
      :data="this.$store.state.modelList"
      v-loading="tableDataLoading"
      style="width: 100%">
      <el-table-column
        prop="model_id"
        :label="$t('message.template-id')">
      </el-table-column>
      <el-table-column
        prop="model_name"
        :label="$t('message.template-name')">
        <template slot-scope="scope">
          <el-button @click="modifyModelName(scope.row.model_id)" type="text" size="small">{{scope.row.model_name}}</el-button>
        </template>
      </el-table-column>
      <el-table-column
        prop="create_time"
        :label="$t('message.create-time')">
      </el-table-column>
      <el-table-column
        :label="$t('message.operation')">
        <template slot-scope="scope">
          <el-button @click="openDetail(scope.row.model_id, scope.row.model_name)" type="text" size="small">{{$t('message.detail')}}</el-button>
          <el-button @click="deleteModel(scope.row.model_id)" type="text" size="small">{{$t('message.delete')}}</el-button>
          <el-button @click="openPreview(scope.row.model_id)" type="text" size="small">{{$t('message.preview')}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--<div class="pagination">-->
    <!--<div>-->
    <!--<el-pagination-->
    <!--background-->
    <!--layout="prev, pager, next"-->
    <!--@current-change="currentPage"-->
    <!--:total="pageSize">-->
    <!--</el-pagination>-->
    <!--</div>-->
    <!--</div>-->
    <!--模板添加界面-->
    <el-dialog
      :title="$t('message.add-template')"
      :visible.sync="addKLineDataVisible">
      <table class="detailTable" border="1">
        <tr>
          <td>{{$t('message.pair-name')}}</td>
          <td>
            <input type="text" v-model="klineData.symbol" placeholder="例：btcusdt">
          </td>
          <td>{{$t('message.get-guantity')}}</td>
          <td>
            <input type="text" v-model="klineData.size" placeholder="1~2000">
          </td>
        </tr>
        <tr>
          <td>{{$t('message.start-time')}}</td>
          <td>
            <el-date-picker
              v-model="klineData.startTime"
              type="datetime"
              :placeholder="$t('message.select-date&time')">
            </el-date-picker>
          </td>
          <td>{{$t('message.end-time')}}</td>
          <td>
            <el-date-picker
              v-model="klineData.endTime"
              type="datetime"
              :placeholder="$t('message.select-date&time')">
            </el-date-picker>
          </td>
        </tr>
        <tr>
          <td>{{$t('message.k-line-time-interval')}}</td>
          <td>
            <el-select id="select" v-model="klineData.period" :placeholder="$t('message.selected')">
              <el-option
                v-for="(item, idx) in periods"
                :key="idx"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </td>
          <td></td>
          <td></td>
        </tr>
      </table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addKLineData"  :loading="addKLineDataLoading">{{$t('message.next-stop')}}</el-button>
      </div>
    </el-dialog>
    <!--生成模板-->
    <el-dialog
      :title="$t('message.generate-template')"
      :visible.sync="getModelVisible"
      width="60%">
      <el-table
        :data="getModelList"
        height="350"
        border
        style="width: 100%">
        <el-table-column
          prop="open"
          :label="$t('message.opening-price')">
        </el-table-column>
        <el-table-column
          prop="close"
          :label="$t('message.closing-price')">
        </el-table-column>
        <el-table-column
          prop="high"
          :label="$t('message.highest-price')">
        </el-table-column>
        <el-table-column
          prop="low"
          :label="$t('message.lowest-price')">
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="setKLineData" v-loading="setKLineDataLoading">{{$t('message.next-stop')}}</el-button>
      </div>
    </el-dialog>
    <!--保存模板-->
    <el-dialog
      :title="$t('message.save-template')"
      :visible.sync="saveModelVisible"
      width="60%">
      <el-table
        :data="saveModelList"
        height="350"
        border
        style="width: 100%">
        <el-table-column
          prop="open_rate"
          :label="$t('message.opening-price-floating-ratio')">
        </el-table-column>
        <el-table-column
          prop="close_rate"
          :label="$t('message.closing-price-floating-ratio')">
        </el-table-column>
        <el-table-column
          prop="high_rate"
          :label="$t('message.highest-price-floating-ratio')">
        </el-table-column>
        <el-table-column
          prop="low_rate"
          :label="$t('message.lowest-price-floating-ratio')">
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveKLineData" v-loading="saveKLineDataLoading">{{$t('message.save-template')}}</el-button>
      </div>
    </el-dialog>
    <!--模板详情-->
    <el-dialog
      :title="$t('message.template-details')+modelInfo"
      :visible.sync="modelDetailVisible"
      @closed="modelDetailClose"
      width="70%">
      <div class="option-btns">
        <el-upload
          ref="upload"
          action="/wm/upload/"
          :show-file-list="false"
          :on-change="readExcel"
          :auto-upload="false">
          <el-button
            slot="trigger"
            icon="el-icon-upload2"
            size="small"
            type="primary">
            {{$t('message.import-model')}}
          </el-button>
        </el-upload>
        <el-button
          size="small"
          type="primary"
          v-on:click="downloadMater()">
          <i class="el-icon-download el-icon--right"></i>{{$t('message.export-model')}}
        </el-button>
      </div>
      <el-table
        :data="modelDetailList"
        v-loading="modelDetailListLoading"
        :cell-style="{textAlign: 'center'}"
        :header-cell-style="{textAlign: 'center'}"
        height="350"
        border
        style="width: 100%">
        <el-table-column
          type="index">
        </el-table-column>
        <el-table-column
          prop="open_rate"
          :label="$t('message.opening-price-floating-ratio')">
          <template slot-scope="scope">
            <input class="inp" type="text" v-model.number="scope.row.open_rate" :disabled="!isEdit">
          </template>
        </el-table-column>
        <el-table-column
          prop="high_rate"
          :label="$t('message.highest-price-floating-ratio')">
          <template slot-scope="scope">
            <input class="inp" type="text" v-model.number="scope.row.high_rate" :disabled="!isEdit">
          </template>
        </el-table-column>
        <el-table-column
          prop="low_rate"
          :label="$t('message.lowest-price-floating-ratio')">
          <template slot-scope="scope">
            <input class="inp" type="text" v-model.number="scope.row.low_rate" :disabled="!isEdit">
          </template>
        </el-table-column>
        <el-table-column
          prop="close_rate"
          :label="$t('message.closing-price-floating-ratio')">
          <template slot-scope="scope">
            <input class="inp" type="text" v-model.number="scope.row.close_rate" :disabled="!isEdit">
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!isEdit" type="primary" @click="isEdit = !isEdit">{{$t('message.edit')}}</el-button>
        <el-button v-if="isEdit" type="primary" @click="saveModelDetail" v-loading="modelDetailLoading">{{$t('message.save')}}</el-button>
        <el-button type="info" @click="modelDetailVisible = false">{{$t('message.cancel')}}</el-button>
      </div>
    </el-dialog>
    <!--预览界面-->
    <el-dialog
      :title="$t('message.preview')"
      @close="previewClose"
      width="70%"
      :visible.sync="kLineVisible">
      <model-k-line :key="isPreview" v-if="isPreview && modelDetailList.length > 0" :list="modelDetailList"/>
    </el-dialog>
  </section>
</template>

<script>
import {KLineData, SetKLineModel, SaveKlineModel, ModelDetail, ModifyModel, ModelDelete, Rename} from '../api/api'
// import { timestampToTime } from '../common/js/util'
import { mapActions, mapState } from 'vuex'
import XLSX from 'xlsx'
import FileSaver from 'file-saver'
import ModelKLine from 'components/modelKLine'
import {isEmpty, modelDetailSort} from '../common/js/util'

export default {
  data () {
    return {
      tableDataLoading: true,
      addKLineDataVisible: false,
      getModelVisible: false,
      saveModelVisible: false,
      modelDetailVisible: false,
      kLineVisible: false,
      addKLineDataLoading: false,
      setKLineDataLoading: false,
      saveKLineDataLoading: false,
      getModelLoading: false,
      modelDetailLoading: false,
      modelDetailListLoading: false,
      pageSize: 1,
      klineData: {
        period: '',
        symbol: '',
        size: '',
        startTime: '',
        endTime: ''
      },
      getModelList: [],
      saveModelList: [],
      periods: [5, 15], // k线时间选择
      isEdit: false,
      modelDetailList: [], // 详情列表
      detailId: '',
      detailName: '',
      isPreview: false
    }
  },
  beforeMount () {
    this.setModelList().then(() => {
      this.tableDataLoading = false
    }).catch(() => {
      this.$message.error(this.$t('message.tip-27'))
    })
  },
  methods: {
    ...mapActions(['setModelList']),
    currentPage () {},
    refreshModelList () {
      this.tableDataLoading = true
      this.setModelList().then(() => {
        this.tableDataLoading = false
      }).catch(() => {
        this.$message.error(this.$t('message.tip-27'))
      })
    },
    addKLineData () {
      console.log(this.klineData)
      let data = this.klineData
      if (isEmpty(data)) {
        this.$message.error(this.$t('message.tip-15'))
        return
      }
      this.addKLineDataLoading = true
      if (new Date(data.startTime) > new Date(data.endTime)) {
        this.$message.error(this.$t('message.tip-28'))
        return false
      }
      data.startTime = Date.parse(new Date(data.startTime)) / 1000
      data.endTime = Date.parse(new Date(data.endTime)) / 1000
      KLineData(data).then((res) => {
        console.log(res)
        if (res.data.code !== 0) {
          this.$message.error(res.data.error)
        } else {
          this.getModelList = res.data.data
          this.addKLineDataLoading = false
          this.addKLineDataVisible = false
          this.getModelVisible = true
        }
      }).catch((err) => {
        console.log('错误')
        console.log(err)
      })
    },
    setKLineData () {
      this.setKLineDataLoading = true
      const param = this.getModelList
      SetKLineModel(param).then(res => {
        console.log(res)
        if (res.data.code !== 0) {
          this.$message.error(res.data.error)
        } else {
          this.saveModelList = res.data.data
          this.setKLineDataLoading = false
          this.getModelVisible = false
          this.saveModelVisible = true
        }
      }).catch(err => {
        console.log(err)
      })
    },
    saveKLineData () {
      this.saveKLineDataLoading = true
      this.$prompt(this.$t('message.new-template-name'), this.$t('message.notification'), {
        confirmButtonText: this.$t('message.confirm'),
        cancelButtonText: this.$t('message.cancel')
      }).then(({ value }) => {
        this.saveKLineDataLoading = false
        const param = {
          modelName: value,
          modelData: this.saveModelList
        }
        SaveKlineModel(param).then(res => {
          console.log(res)
          if (res.data.code !== 0) {
            this.$message.error(res.data.error)
          } else {
            this.setModelList().then(() => {
              this.tableDataLoading = false
            }).catch(() => {
              this.$message.error(this.$t('message.tip-29'))
            })
            this.saveModelVisible = false
          }
        }).catch(err => {
          console.log(err)
        })
        this.$message({
          type: 'success',
          message: this.$t('message.tip-30') + value
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('message.tip-31')
        })
      })
    },
    openDetail (id, name) {
      this.detailId = id
      this.detailName = name
      this.modelDetailVisible = true
      this.modelDetailListLoading = true
      this.getDetailList(id)
    },
    saveModelDetail () {
      this.modelDetailLoading = true
      let data = {
        modelId: this.detailId + '',
        modelData: this.modelDetailList
      }
      ModifyModel(data).then((res) => {
        console.log(res)
        if (res.data.code !== 0) {
          this.modelDetailLoading = false
          this.$message({
            type: 'error',
            message: res.data.error
          })
        } else {
          this.setModelList().then(() => {
            this.tableDataLoading = false
          }).catch(() => {
            this.$message.error(this.$t('message.tip-29'))
          })
          this.modelDetailLoading = false
          this.modelDetailVisible = false
          this.$message({
            type: 'success',
            message: this.$t('message.tip-14')
          })
        }
      }).catch(() => {
        this.$message({
          type: 'error',
          message: this.$t('message.tip-25')
        })
      })
    },
    deleteModel (id) {
      let param = {modelId: id + ''}
      this.$confirm(this.$t('message.tip-9'), this.$t('message.notification'), {
        confirmButtonText: this.$t('message.confirm'),
        cancelButtonText: this.$t('message.cancel'),
        type: 'warning'
      }).then(() => {
        ModelDelete(param).then((res) => {
          console.log(res)
          if (res.data.code === 0) {
            this.setModelList().then(() => {
              this.tableDataLoading = false
            }).catch(() => {
              this.$message.error(this.$t('message.tip-11'))
            })
            this.$message({
              type: 'success',
              message: this.$t('message.tip-5')
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('message.tip-4')
        })
      })
    },
    modelDetailClose () {
      this.isEdit = false
    },
    modifyModelName (id) {
      this.$prompt(this.$t('message.new-template-name'), this.$t('message.notification'), {
        confirmButtonText: this.$t('message.confirm'),
        cancelButtonText: this.$t('message.cancel'),
        inputPattern: /^[\s\S]*.*[^\s][\s\S]*$/,
        inputErrorMessage: this.$t('message.tip-47')
      }).then(({ value }) => {
        console.log(id)
        let param = {modelId: id, modelName: value}
        Rename(param).then(res => {
          if (res.data.code !== 0) {
            this.$message.error(res.data.error)
          } else {
            this.refreshModelList()
            this.$message({
              type: 'success',
              message: this.$t('message.tip-30') + value
            })
          }
        }).catch(() => {
          this.$message({
            type: 'error',
            message: this.$t('message.tip-25')
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('message.tip-31')
        })
      })
    },
    openPreview (id) {
      this.isPreview = true
      this.kLineVisible = true
      this.getDetailList(id)
    },
    previewClose () {
      this.isPreview = false
    },
    readExcel (file) {
      this.modelDetailListLoading = true
      const fileReader = new FileReader()
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result
          const workbook = XLSX.read(data, {
            type: 'binary'
          })
          for (let sheet in workbook.Sheets) {
            const sheetArray = XLSX.utils.sheet_to_json(workbook.Sheets[sheet])
            console.log(sheetArray)
            this.modelDetailList = sheetArray
          }
        } catch (e) {
          this.$message.warning('文件类型不正确！')
          return false
        }
      }
      fileReader.readAsBinaryString(file.raw)
      this.modelDetailListLoading = false
      this.isEdit = true
    },
    downloadMater () {
      const defaultCellStyle = {
        font: { name: 'Times New Roman',
          sz: 16,
          color: { rgb: '#FF000000' },
          bold: false,
          italic: false,
          underline: false
        },
        alignment: { vertical: 'center', horizontal: 'center', indent: 0, wrapText: true },
        border: {
          top: { style: 'thin', color: { 'auto': 1 } },
          right: { style: 'thin', color: { 'auto': 1 } },
          bottom: { style: 'thin', color: { 'auto': 1 } },
          left: { style: 'thin', color: { 'auto': 1 } } }
      }
      const wopts = {bookType: 'xlsx', bookSST: false, type: 'binary', defaultCellStyle: defaultCellStyle, showGridLines: false}
      const wb = { SheetNames: ['Sheet1'], Sheets: {}, Props: {} }
      let data = modelDetailSort(this.modelDetailList)
      wb.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(data)

      // 创建二进制对象写入转换好的字节流
      let tmpDown = new Blob([this.s2ab(XLSX.write(wb, wopts))], { type: 'application/octet-stream' })
      FileSaver.saveAs(tmpDown, this.detailName + '.xlsx')
    },
    s2ab (s) {
      if (typeof ArrayBuffer !== 'undefined') {
        let buf = new ArrayBuffer(s.length)
        var view = new Uint8Array(buf)
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF
        return buf
      } else {
        let buf = new Array(s.length)
        for (let i = 0; i !== s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF
        return buf
      }
    },
    getDetailList (id) {
      ModelDetail({modelId: id}).then(res => {
        console.log(res)
        if (res.data.code !== 0) {
          this.$message.error(this.$t('message.tip-32'))
        } else {
          if (res.data.data) {
            this.modelDetailList = JSON.parse(res.data.data)
            this.$store.commit('SET_PREVIEW_DATA', this.modelDetailList)
            this.modelDetailListLoading = false
          }
        }
      })
    }
  },
  computed: {
    ...mapState(['modelList']),
    modelInfo () {
      return '(ID:' + this.detailId + '\n\n\n\n' + this.$t('message.template-name') + ':' + this.detailName + ')'
    }
  },
  components: {
    ModelKLine
  }
}

</script>

<style scoped lang="scss">
  .pagination {
    overflow: hidden;
    margin-top: 20px;
    div {
      float: right;
      width: 400px;
    }
  }
  .dialog-footer {
    text-align: center;
  }
  .option-btns {
    display: flex;
    justify-content: flex-end;
    button {
      margin: 10px 10px;
    }
  }
</style>
